import React from 'react'
import { useEffect, useState } from 'react';
import { useNavigate ,useLocation } from "react-router";
import { Layout, Menu } from 'antd';
import './index.css'
import {
  UserOutlined,
} from '@ant-design/icons';
import { connect } from 'react-redux';
import axios from 'axios';

const { Sider } = Layout;
const { SubMenu } = Menu;

const iconList = {
  "/home": <UserOutlined />,
  "/user-manage": <UserOutlined />,
  "/user-manage/list": <UserOutlined />,
  "/right-manage": <UserOutlined />,
  "/right-manage/role/list": <UserOutlined />,
  "/right-manage/right/list": <UserOutlined />
  //.......
}

function SideMenu(props) {
  const {role:{rights}} = JSON.parse(localStorage.getItem("token"))
  let navigate = useNavigate();
  let location = useLocation();
  const selectKeys = [location.pathname];
  const openKeys = ["/" + location.pathname.split("/")[1]];
  const [menu, setMenu] = useState([])

  useEffect(() => {
    axios.get('http://localhost:5000/rights?_embed=children').then(res => {
      setMenu(res.data)
    })
  }, [])

  const checkPagePermission = (item) => {
    return item.pagepermisson && rights.includes(item.key)
  }

  
  const renderMenu = (menuList) => {
    return menuList.map(item => {
      if (item.children?.length && checkPagePermission(item)) {
        return <SubMenu key={item.key} icon={iconList[item.key]} title={item.title}>
          {renderMenu(item.children)}
        </SubMenu>
      }
      return checkPagePermission(item) && <Menu.Item key={item.key} icon={iconList[item.key]} onClick={() => navigate(item.key)}>{item.title}</Menu.Item>

    })

  }

  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: "flex", height: "100%", "flexDirection": "column" }}>
        <div className="logo">系统</div>
        <div style={{ flex: 1, "overflow": "auto" }}>
          <Menu theme="dark" mode="inline" selectedKeys={selectKeys} defaultOpenKeys={openKeys}>
            {renderMenu(menu)}
          </Menu>
        </div>
      </div>
    </Sider>
  )
}
const mapStateToProps = ({CollApsedReducer:{isCollapsed}})=>{
  return{
    isCollapsed
  }
}
export default connect(mapStateToProps)(SideMenu)
